package com.woyou.ui.activity.orderdetail;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.woyou.bean.Info;
import com.woyou.bean.OrderDetail;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.OrderDefaultReq;
import com.woyou.controller.ISceneSwitchView;
import com.woyou.controller.SuperController;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.HomeActivity_;
import com.woyou.ui.activity.LoginActivity_;
import com.woyou.ui.activity.PayOnlineActivity;
import com.woyou.ui.activity.ShopInfoActivity;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.ui.view.SuperUI;
import com.woyou.utils.InstallUtils;
import com.woyou.utils.ShareUtils;

public class OrderDetailActController extends SuperController implements ISceneSwitchView {
	
	private ErrorHintView mErrorHintView;
	private FrameLayout mContainer;
	
	private OrderDetailActivity mView;
	
	private static final int NOTIFY = 0x100;
	private long mTime;
	private Timer mTimer;
	private TimerTask timerTask;
	
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat format = new SimpleDateFormat("mm分ss秒");
	
	public OrderDetailActController(Context context, SuperUI superUI) {
		super(context, superUI);
		mView = (OrderDetailActivity) superUI;
		
		mErrorHintView = mView.mErrorHintView;
		mContainer = mView.mContainer;
	}
	
	/*开始倒计时*/
	public void startCountDown(OrderDetail mOrderDetail){
		mTime = (long) mOrderDetail.getInvalidTime() * 1000;
		if(mTimer!=null){
			mTimer.cancel();
			mTimer = null;
			
			timerTask.cancel();
		}
		timerTask = new TimerTask() {
			
			@Override
			public void run() {
				mTime = mTime - 1000;
				mHandler.sendEmptyMessage(NOTIFY);
			}
		};
		
		mTimer = new Timer();
		mTimer.schedule(timerTask, 0, 1000);
	}
	
	private Handler mHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == NOTIFY) {
				if (mTime <= 0) {
					mView.downTimeText.setText("支付超时，请重新下单！");
					mView.downTimeText.setTextColor(Color.RED);
					mTimer.cancel();

				} else
					mView.downTimeText.setText("请在" + format.format(new Date(mTime)) + "之内完成支付");
			}
			return false;
		}
	});
	
	@SuppressWarnings("rawtypes")
	public void handlOnClick(View v) {
		switch (v.getId()) {
		case R.id.back_left:
			// 左边返回
			mView.backOperate();
			break;
			
		case R.id.back_right:
			// 右边返回
			Map<String, String> map = new HashMap<String, String>();
			map.put("sId", mView.mOrderDetail.getsId());
			map.put("sName", mView.mOrderDetail.getsName());

			Info<Map<String, String>> inf = new Info<Map<String, String>>(map);
			inf.setOrigin(OrderDetailActivity.class);
			openActivity(ShopInfoActivity.class, inf);
			mView.finish();
			break;
		
		case R.id.contents_again: 
			// 再来一单
			break;

		case R.id.contents_shareorder: 
			// 分享订单
			ShareUtils shareUtils = ShareUtils.getInstance(mActivity);
			mView.mController = shareUtils.getmController();
			shareUtils.setShareOrder(mView.oId);
			mView.mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ,
					SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA);
			mView.mController.openShare(mActivity, false);
			break;

		case R.id.info_contactshops: 
			// 联系店铺
			if (mView.mOrderDetail != null) {
				callPhone(mView.mOrderDetail.getsPhone());
			}
			break;

		case R.id.info_othershops: 
			// 查看其他店铺
			Info<Class> info = new Info<Class>(ShopsFragment_.class);
			openActivity(HomeActivity_.class, info);
			break;

		}
	}
	
	/**加载订单详情 , 我要支付*/
	public void loadOrderDetailJumpPay(final String oId) {
		if (!NetWorkCenter.isNetworkConnected(mContext)) {
			showToast("请检查网络");
			return;
		}

		executeTask(new Runnable() {
			
			@Override
			public void run() {
				try {
					OrderDefaultReq orderDefaultReq = new OrderDefaultReq();
					UserInfo info = mUserModel.getUserInfo(); 
					
					if (info != null && !info.getuId().equals("")) {
						orderDefaultReq.setoId(oId);
						orderDefaultReq.setuId(info.getuId());
						orderDefaultReq.setPwd(info.getPwd());
						final Result<OrderDetail> result = mOrderModel.v2_3queryOrderDetail(orderDefaultReq);
						if (result != null && result.getCode() == 1) {
							runOnUI(new Runnable() {
								
								@Override
								public void run() {
									OrderDetail mOrderDetail = result.getData();
									Info<OrderDetail> info = new Info<OrderDetail>();
									info.setData(mOrderDetail);
									info.setOrigin(OrderDetailActivity.class);
									openActivity(PayOnlineActivity.class, info);
									mView.finish();
								}
							});
						} else {
							showToastOnUI("result");
						} 
					} else {
						showToastOnUI("登录后方可查看订单详s情");
						openActivity(LoginActivity_.class, null);
						mView.finish();
					}
				} catch (RetrofitError e) {
					e.printStackTrace();
				} 
			}
		});
	}
	
	public void fillOrderState(int state, TextView orderStatus){
		switch (state) {
		case State.NEW_ORDER:
			// 新订单
			orderStatus.setText("新订单");
			break;
		case State.PUSH_SUCCEED:
			// 推送成功
			orderStatus.setText("等待接单");
			break;
		case State.NOT_CONNECTED:
			// 未接通
			orderStatus.setText("订单未接通");
			break;
		case State.NO_RESPONSE:
			// 接通后未应答
			orderStatus.setText("订单未应答");
			break;
		case State.REFUSE:
			// 已拒绝
			orderStatus.setText("订单已拒绝");
			break;
		case State.OUT_STOCK:
			// 返单
			orderStatus.setText("订单已返单");
			
		case State.CONFIRMED:
			// 已确认
			orderStatus.setText("订单已接受");
			break;
		case State.CANCELLED:
			// 已取消
			orderStatus.setText("订单已取消");
			break;
		case State.SENT_OUT:
			// 已送出
			orderStatus.setText("订单已送出");
			break;
		case State.DELICERED:
			// 已送达
			orderStatus.setText("已确认收货");
			break;
		case State.COMMENTED:
			// 已评价
			orderStatus.setText("订单已评价");
			break;
		case State.AUTO_COMPLETE:
			// 自动完成
			orderStatus.setText("自动完成");
			break;
		case State.CANCELLATION:
			// 申请取消中
			orderStatus.setText("申请取消中");
			break;
		case State.NEW_ORDER_ONLINEPAY:
			//待支付
			orderStatus.setText("订单未支付");
			break;
		case State.CANCELLED_ONLINEPAY:
			// 未支付被取消
			orderStatus.setText("订单已取消");
			break;
		case State.PAID:
			// 已支付
			orderStatus.setText("等待接单");
			break;
		default:
			break;
		}
	}
	
	/*拨打电话*/
	private void callPhone(String str) {
		// 用intent启动拨打电话
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
		if(InstallUtils.isIntentAvailable(mContext, intent)){
			mContext.startActivity(intent);
		}
	}
	
	@Override
	public boolean backOperate() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void showContent() {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				mErrorHintView.hideLoading();
				mContainer.setVisibility(View.VISIBLE);
			}
		});
	}

	@Override
	public void networkError() {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				mContainer.setVisibility(View.GONE);
				mErrorHintView.hideLoading();
				mErrorHintView.netError(new OperateListener() {
					@Override
					public void operate() {
						mErrorHintView.loadingData();
						mView.loadOrderDetail(mView.oId);
					}
				});
			}
		});
		
	}

	@Override
	public void loadFailure() {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				mContainer.setVisibility(View.GONE);
				mErrorHintView.hideLoading();
				mErrorHintView.loadFailure(new OperateListener() {
					@Override
					public void operate() {
						mErrorHintView.loadingData();
						mView.loadOrderDetail(mView.oId);
					}
				});
			}
		});
	}

	@Override
	public void locationFailure() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void outTime() {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				mContainer.setVisibility(View.GONE);
				mErrorHintView.hideLoading();
				mErrorHintView.timeOut(new OperateListener() {
					@Override
					public void operate() {
						mErrorHintView.loadingData();
						mView.loadOrderDetail(mView.oId);
					}
				});
			}
		});
	}

	@Override
	public void noData() {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				mContainer.setVisibility(View.GONE);
				mErrorHintView.hideLoading();
				mErrorHintView.loadNoDetail();
			}
		});
	}

	@Override
	public void reset() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void loading() {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				mErrorHintView.loadingData();
			}
		});
	}

	@Override
	public void handleError(final RetrofitError e) {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				switch (e.getKind()) {
				case HTTP:
					outTime();
					break;
				case CONVERSION:
					loadFailure();
					break;
				case NETWORK:
					networkError();
					break;
				case UNEXPECTED:
					loadFailure();
					break;
				default:
					break;
				}
			}
		});
	}

}
